package zero.tech.games.gate.interceptor;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;

import zero.tech.core.data.Resp;
import zero.tech.core.data.SimpleUser;
import zero.tech.games.common.Code;
import zero.tech.games.common.RedisConsts;
import zero.tech.games.gate.util.PipeiUtil;
import zero.tech.wsnet.data.CheckPipeiQueue;

/**
 * 像提现这种需要减少资金账户的一定要进行拦截最后的房间信息,
 *  如果有最后的房间信息 即为在游戏当中需要告知客户端进行拉入原来的游戏房间
 * 
 * 特别注意:需要各个子游戏各自维护自己游戏的最后房间信息 UserLastRoom缓存
 * 
 * @author ASUS
 *
 */
@Component
public class CheckPipeiQueueInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	private PipeiUtil pipeiUtil;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		boolean checkPipeiQueue = false;
		if (!(handler instanceof HandlerMethod)) {
			return true;
		} else {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			if (handlerMethod.hasMethodAnnotation(CheckPipeiQueue.class)) {
				checkPipeiQueue = true;
			}
		}
		if (checkPipeiQueue) {
			SimpleUser player = getLoginUser(request);
			int uid = player.getUid();
			//检查是否再匹配队列中
			if(pipeiUtil.inQueue(uid)) {
				response.getWriter().write(
						JSONObject.toJSONString(Resp.build(Code.BE_IN_PIPEIQUEUE, "正在匹配中...")));
				return false;
			}
		}
		return true;
	}
	
	public SimpleUser getLoginUser(HttpServletRequest request) {
		SimpleUser simpleUser=null;
		String str=request.getHeader(RedisConsts.GATEWAY_USER);
		if(StringUtils.isNotBlank(str)) {
			try {
				str=URLDecoder.decode(str, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			simpleUser=JSONObject.parseObject(str, SimpleUser.class);
		}
		return simpleUser;
	}
}
